package com.fkdx.service;

import com.alibaba.fastjson.JSON;
import com.fkdx.common.enums.DigiEnum;
import com.fkdx.common.enums.SysStatusEnum;
import com.fkdx.dao.condition.VoucherCondition;
import com.fkdx.dao.entity.Voucher;
import com.fkdx.dao.entity.PageResult;
import com.fkdx.dao.mapper.VoucherMapper;
import com.fkdx.service.dto.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.google.common.collect.Lists;
import com.fkdx.common.dto.sys.CurrentUserDTO;
import com.fkdx.common.sys.SecurityHelper;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Date;

/**
 * @author: create by wsh 
 * @date:2022/8/20
 */
@Log4j2
@Service()
public class VoucherService {

    @Resource
    private VoucherMapper voucherMapper;

    @Resource
    private TaskService taskService;

    @Resource
    private DictService dictService;

    @Resource
    private DigiService digiService;

    /**
     * 获取粮食品种集合     *     * @param req     * @return
     */
    public PageResult<VoucherQueryResp> getVoucherList(VoucherQueryReq req) {
        CurrentUserDTO principal = SecurityHelper.getPrincipal();
        VoucherCondition condition = new VoucherCondition();
        BeanUtils.copyProperties(req, condition);
        condition.setTenantId(principal.getTenantId());
        List<Voucher> list = voucherMapper.selectAll(condition);
        PageResult<VoucherQueryResp> results = new PageResult<>(list, (m) -> {
              VoucherQueryResp res = new VoucherQueryResp();
              BeanUtils.copyProperties(m, res);
              return res;
            });
        return results;
    }

    /**
     * 获取详情     *     * @param id     * @return
     */
    public VoucherQueryResp getVoucherForm(Long id) {
        VoucherQueryResp resp = new VoucherQueryResp();
        Voucher voucher = voucherMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(voucher, resp);
        return resp;
    }

    /**
     * 新增、修改     *     * @param req
     */
    public void saveVoucherForm(VoucherReq req) {
        Voucher v = voucherMapper.selectByPrimaryKey(req.getId());
        Voucher voucher = new Voucher();
        BeanUtils.copyProperties(req, voucher);
        voucher.setModificationUserId(0L);
        voucher.setModificationUserName("system");
        voucher.setNum(v.getNum() != null ?  (v.getNum() + 1) : 1);
        voucherMapper.updateSelective(voucher);
        TaskQueryResp t = taskService.getTaskForm(req.getTid());
        DigiEnum d = DigiEnum.AMAZON;
        if (t.getType() == 5) {
            d = DigiEnum.APPLE;
        } else if (t.getType() == 6) {
            d = DigiEnum.GOOGLE;
        }
        TaskReq treq = new TaskReq();
        try {
            log.info("Voucher信息：【{}】,【{}】,【{}】", JSON.toJSONString(d),JSON.toJSONString(t), JSON.toJSONString(voucher));
            String[] r = this.test(d, voucher.getVoucher(), t.getPrice());
            treq.setBalance(r[0]);
            treq.setStatus(1);
            treq.setResult(r[1]);
        } catch (RuntimeException ex) {
            treq.setStatus(4);
            treq.setResult(ex.getMessage());
        }
        treq.setId(req.getTid());
        taskService.addTaskForm(treq);
    }

    /**
     * 删除     *     * @param id
     */
    public void removeVoucherList(Long[] id) {
        voucherMapper.updateByIds(Lists.newArrayList(id));
    }

    public Voucher sysVoucher(Long id) {
        log.info("id信息：【{}】", id);
        TaskQueryResp t = taskService.getTaskForm(id);
        Voucher voucher = voucherMapper.selectByUid(t.getCreateUserId(), "digi");
        log.info("Voucher信息：【{}】", JSON.toJSONString(voucher));
        if (voucher != null) {
            if (StringUtils.isEmpty(voucher.getVoucher())) {
                voucher.setNum(null);
            } else {
                if (voucher.getNum() != null) {
                    DictQueryResp d = dictService.getDictCode("digiyxq");
                    if (Integer.parseInt(d.getDataCode()) < voucher.getNum()) {
                        voucher.setNum(0);
                    }
                }
                VoucherReq req = new VoucherReq();
                BeanUtils.copyProperties(voucher, req);
                req.setTid(id);
                this.saveVoucherForm(req);
            }

        } else {
            Date d = new Date();
            voucher = new Voucher();
            voucher.setUid(t.getCreateUserId());
            voucher.setType("digi");
            voucher.setCreated(d);
            voucher.setModified(d);
            voucher.setCreateUserId(t.getCreateUserId());
            voucher.setCreateUserName(t.getCreateUserName());
            voucher.setModificationUserId(t.getCreateUserId());
            voucher.setModificationUserName(t.getCreateUserName());
            voucher.setTenantId(t.getTenantId());
            voucher.setYn(SysStatusEnum.YES.getStatus());
            voucherMapper.insert(voucher);
        }
        return voucher;
    }

    public String[] test(DigiEnum d, String c,Integer price) {
        String[] r = new String[2];

        //获取余额
        String[] res = digiService.getBalance(d.getBurl(), c);
        if(price > Integer.parseInt(res[0])) {
            throw new RuntimeException("余额不足");
        }
        //交换接口
        String exchange = digiService.getExchange(d.getJurl(), c, res[1], price.toString(), d);
        String code = digiService.getResult(exchange, c,d.getType());
        r[0] = res[0];
        r[1] = code;
        log.info("结果信息：【{}】", JSON.toJSONString(r));
        return r;
    }
}
